﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace UdpMulticastReceiver
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            // 组播地址
            IPAddress multicastAddress = IPAddress.Parse("239.0.0.1");
            int port = 12345;

            // 创建UdpClient
            using (UdpClient udpClient = new UdpClient(new IPEndPoint(IPAddress.Any, port)))
            {
                // 设置组播TTL为32，可以跨路由
                udpClient.JoinMulticastGroup(multicastAddress, 32);

                var endpoint = new IPEndPoint(IPAddress.Any, 0);
                // 接收数据
                while (true)
                {
                    byte[] buffer = udpClient.Receive(ref endpoint);
                    string message = Encoding.UTF8.GetString(buffer);
                    Console.WriteLine("收到数据: " + message);
                }
            }
        }
    }
}